function limitConcurrency(tasks, limit) {
    const results = [];
    let current = 0;
    let completed = 0;

    return new Promise((resolve, reject) => {
        function runTask(index) {
            if (index >= tasks.length) {
                if (completed === tasks.length) {
                    resolve(results);
                }
                return;
            }

            current++;
            tasks[index]()
                .then(result => {
                    results[index] = result;
                })
                .catch(error => {
                    results[index] = { error: error.message };
                })
                .finally(() => {
                    completed++;
                    current--;
                    runTask(index + limit);
                });
        }

        // 启动前 limit 个任务
        for (let i = 0; i < Math.min(limit, tasks.length); i++) {
            runTask(i);
        }
    });
}

// 使用
const tasks = [
    () => delay(1000).then(() => '任务1'),
    () => delay(2000).then(() => '任务2'),
    () => delay(1000).then(() => '任务3'),
    () => delay(1500).then(() => '任务4'),
    () => delay(1000).then(() => '任务5')
];

limitConcurrency(tasks, 2)
    .then(results => console.log(results));